<?php
/**
 * This file is part of DomBankLink.
 * 
 * DomBankLink is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * DomBankLink is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with DomBankLink.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @link http://inditel.ee/
 * @copyright 2007-2009 Inditel Meedia OÜ
 * @author Oliver Leisalu <oliver@inditel.ee>
 */

/**
 * This class is not finished. It is just copied from BankLink library. (OLD)
 * @package PankLink
 * @author Jesper Saron
 */
final class DomBankLink_EstCard extends DomBankLink {
	
	/**
	* Private key file path
	* @var String
	*/
	protected $privateKey;
	/**
	* Request/Public key file path
	* @var String
	*/
	protected $requestKey;
	/**
	* Reseller identification code
	* @var String
	*/
	protected $resellerId;
	/**
	* Server to where request is sent.
	* @var String
	*/
	protected $serverUrl;
	/**
	* Url to where user is sent back from bank
	* @var String
	*/
	protected $callbackUrl;
	/**
	 * @var String
	 */
	protected $language;
	
	/**
	 * Function returns all the input fields required by the bank using BankPayment object.
	 *
	 * @param BankPayment $payment
	 * @return string HTML including input=hidden tags
	 */
	public function sendToBank( $callBackId, BankPayment $payment) {
		if (strpos($payment->price, ",")) {
			$payment->price = (float)str_replace(",", ".", $payment->price);
		}
		
		$rsField = array(
			'action'    => 'gaf',
            'ver'      => "002",
            'id'     => (string)$this->resellerId,
			'ecuno'        => sprintf("%012s", $callBackId),
            'eamount'       => sprintf("%012s", round($payment->price*100)),
			'cur' 	 => strtoupper($payment->currency),
			'datetime'     => (string)date("YmdHis"),
			'lang'        => $this->language,
       	);
       	$sMacBase =
       		$rsField['ver'] .
       		sprintf("%-10s", $rsField['id']) .
       		$rsField['ecuno'] .
       		$rsField['eamount'] .
       		$rsField['cur'] .
       		$rsField['datetime'];
       	$sSignature = sha1($sMacBase);

       	$flKey = openssl_get_privatekey(file_get_contents($this->privateKey));

		if (!openssl_sign($sMacBase, $sSignature, openssl_get_privatekey(file_get_contents($this->privateKey)))) {
			trigger_error ("Unable to generate signature", E_USER_ERROR);
		}
    	$rsField['mac'] = bin2hex($sSignature);
		
    	$html = '';
    	foreach ($rsField as $ixField => $fieldValue) {
    		$html .= '<input type="hidden" name="' . $ixField . '" value="' . htmlspecialchars(iconv($this->inputEncoding, $this->nOutputEncoding, $fieldValue)) . '" />' . "\n";
    	}
    	
    	echo self::getFormBase($this, $html);
		die();
	}

	/**
	 * Function that processes the callback from the bank and returns BankPayment objects with isSuccessful
	 * (and other applicable) parameters filled according to the answers from the bank.
	 *
	 * @return BankPayment
	 */
	protected function handleReplay() {
		$rsField = array();

	    foreach ((array)$_REQUEST as $ixField => $fieldValue) {
            $rsField[$ixField] = $fieldValue;
	    }

		$sSignatureBase =
			sprintf("%03s", $rsField['ver']) .
			sprintf("%-10s", $rsField['id']) .
			sprintf("%012s", $rsField['ecuno']) .
			sprintf("%06s", $rsField['receipt_no']) .
			sprintf("%012s", $rsField['eamount']) .
			sprintf("%3s", $rsField['cur']) .
			$rsField['respcode'] .
			$rsField['datetime'] .
			sprintf("%-40s", $rsField['msgdata']) .
			sprintf("%-40s", $rsField['actiontext']);
			
	    function hex2str($hex) {
			for($i=0;$i<strlen($hex);$i+=2) $str.=chr(hexdec(substr($hex,$i,2)));
			return $str;
		}

		$mac = hex2str($rsField['mac']);
		$sSignature = sha1($sSignatureBase);
		$flKey = openssl_get_publickey(file_get_contents($this->requestKey));
		
		// Invalid signature
		if (!openssl_verify ($sSignatureBase, $mac, $flKey)) {
			return array('status' => 4, 'logId' => (int)$rsField['ecuno'], 'bankError'=>'', 'bankErrorStr'=>'Receiptnr: '.$rsField['receipt_no'] );

		// Payment was cancelled
		} else if ($rsField['receipt_no'] == 000000)  {
			return array('status' => 3, 'logId' => (int)$rsField['ecuno'], 'bankError'=>'', 'bankErrorStr'=>'Receiptnr: '.$rsField['receipt_no'] );
		// Payment successful
		} else {
			return array('status' => 1, 'logId' => (int)$rsField['ecuno'], 'bankError'=>'', 'bankErrorStr'=>'Receiptnr: '.$rsField['receipt_no']);
			
		}
	}
}
?>